<?php
namespace app\api\controller;

use app\common\controller\ApiBase;
use app\common\model\Company;
use app\common\model\User as UserModel;
use app\common\model\KfUser;
use app\common\model\KfUserComment;
use app\common\model\KfSession;
use app\common\model\KfSessionMessage;
use app\common\model\KfFaq;

use think\Cache;
use think\facade\Log;

class Wechat extends ApiBase
{
    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 生成带参二维码
     * @return 二维码链接
     */
    public function qrcode()
    {
        
        if(!isset($this->param['key']) || empty($this->param['key'])){
            $this->ajaxReturn(false,'缺少KEY');
        }
        $key=$this->param['key'];
        //1永久 2临时
        $type = isset($this->param['type']) ? $this->param['type'] : 2;
        $cpm = ((defined('SANDBOX') && SANDBOX) || (defined('DEBUG') && DEBUG)) ? 7 : 6;
        $this->setCpmConfig($cpm);
        $out_url = \Wechat::getQrcodeurl($key, $type);
        $rs = $this->imgtobase64($out_url);
        $this->ajaxReturn($rs);
    }

    private function imgtobase64($img = '', $imgHtmlCode = true)
    {
        $imageInfo = getimagesize($img);
        return 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img)));;
    }

    /**
     * 关注事件回复消息
     * @return
     */
    public function responseMsg()
    {
        if (!isset($this->get['cpm'])) {
            $this->ajaxReturn('error cpm');
        }
        $this->setCpmConfig((int)$this->get['cpm']);
        if(isset($_GET['echostr'])){
            if(\Wechat::checkSignature()){
                echo $_GET['echostr'];
            }
            exit();
        }
        $postArr = file_get_contents('php://input');
        Log::write($postArr, 'wx');
        if(empty($postArr)){
            echo '';
        }else{
            $postObj = simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $postArr = json_decode(json_encode($postObj), true);
            $postArr['cpm']=(int)$this->get['cpm'];
            switch (strtolower($postArr['MsgType'])) {
                case 'event':
                    if(strtolower($postArr['Event']) == 'subscribe' || strtolower($postArr['Event']) == 'scan'){//关注 或者第二次扫码
                        $this->subscribeResponse($postArr);
                    }elseif(strtolower($postArr['Event']) == 'click'){//点击事件
                        $this->sendChooseMenu($postArr);
                    }elseif(strtolower($postArr['Event']) == 'kf_close_session'){//会话关闭 
                        $this->sendCommentMenu($postArr);
                    }
                    break;
                case 'text':
                    $cache_key='comment_'.$postArr['FromUserName'].'_'.$postArr['cpm'];
                    $session_id=cache($cache_key);
                    if($postArr['Content']=='kfht'){
                        $href=get_full_host().'/api/kf/index?cpm='.$this->get['cpm'];
                        $content = sprintf("<a href='%s'>授权登录</a>", $href);

                        \Wechat::sendCustomerMsg($postArr['FromUserName'],'text',$content);
                    }elseif(!empty($session_id) && in_array($postArr['Content'],['满意','不满意','1、满意','2、不满意','1','2'])){
                        $session=KfSession::where('id',$session_id['session_id'])->find();
                        if(!empty($session)){
                            $arr=['满意'=>1,'1'=>1,'1、满意'=>1,'不满意'=>2,'2、不满意'=>2,'2'=>2];
                            KfUserComment::create(['cpm'=>$session['cpm'],'kf_openid'=>$session['kf_openid'],'user_openid'=>$session['user_openid'],'status'=>$arr[$postArr['Content']],'content'=>$postArr['Content'],'time'=>time()]);
                        }
                        cache($cache_key,NULL);
                        \Wechat::sendCustomerMsg($postArr['FromUserName'],'text','感谢您的评价');
                    }else{
                        if(in_array($postArr['Content'],['1','2','3','4'])){//发送内容为1,2,3,4中的一个 对应选择问题的序号
                            $group=\Wechat::$customer_group;
                            $key=$postArr['Content']-1;
                            if(array_key_exists($key,$group) && !empty($group[$key]['id'])){
                                $postArr['bizmsgmenuid']=$group[$key]['id'];
                            }
                        }
                        $this->newCreateSession($postArr);
                    }
                    break;
                case 'video':
                case 'shortvideo':
                case 'image':
                case 'voice':
                case 'link':
                    $this->newCreateSession($postArr);
                    break;
                
                default:
                    # code...
                    break;
            }
            // if(strtolower($postArr['MsgType']) == 'event'){
            //     $this->subscribeResponse($postArr);
            //     if(strtolower($postArr['Event']) == 'click'){//点击事件
            //         $this->sendChooseMenu($postArr);
            //     }elseif(strtolower($postArr['Event']) == 'kf_close_session'){//会话关闭 
            //         $this->sendCommentMenu($postArr);
            //     }
            // }elseif(strtolower($postArr['MsgType']) == 'text'){
                
            //     if(array_key_exists('bizmsgmenuid',$postArr) && $postArr['bizmsgmenuid']){//点击菜单
            //         $this->clickMenuResponse($postArr);
            //     }
            //     if(in_array($postArr['Content'],['1','2','3','4'])){//发送内容为1,2,3,4中的一个 对应选择问题的序号
            //         $group=\Wechat::$customer_group;
            //         $key=$postArr['Content']-1;
            //         if(array_key_exists($key,$group) && !empty($group[$key]['id'])){
            //             $postArr['bizmsgmenuid']=$group[$key]['id'];
            //             $this->clickMenuResponse($postArr);
            //         }
            //     }
            //     $this->newCreateSession($postArr);
            // }elseif (strtolower($postArr['MsgType']) == 'image') {
            //     $this->newCreateSession($postArr);
            // }
        }

    }

    /**
     * 关注回复
     */
    private function subscribeResponse($postArr){
        $icon = get_full_host() . '/user/image/regicon.jpg';
        if(strtolower($postArr['Event']) == 'subscribe' || strtolower($postArr['Event']) == 'scan'){
            $toUser = $postArr['FromUserName'];
            $fromUser = $postArr['ToUserName'];
            $EventKey = $postArr['EventKey'];
            //参数前缀qrscene_
            $key=!empty($EventKey) ? str_replace('qrscene_','',$EventKey) : false;
            $user = $key ? UserModel::get(['key' => $key]) : false;
            if (!empty($user)){
                $href = sprintf("%s/web/oauth/index?act=spread&key=%s", get_full_host(), $key);
                $content = sprintf("@%s,诚邀你成为超级合伙人！\n\n活动最后7天，每邀请一人：\n\n你得<a href='%s'>8</a>元，他得<a href='%s'>30</a>元！你也可以哦！\n\n👇点击下方链接，领取专属奖励！", $user["uname"], $href, $href);
            }else{
                $content = "亲爱的合伙人,终于等到你，还好我没放弃！\n欢迎加入我们\n来这里带你一起轻松躺赚\n结交有腔调、有共识的朋友\n做有尊严的生意\n共创环保新事业\n【如有疑问 详询客服】tangmaokefu\n";
            }
            $time = time();
            $msgType = 'text';
            $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                        </xml>";

            $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
            echo '';
            $post['touser'] = $toUser;
            $post['msgtype'] = 'text';
            $post['text'] = [
                'content' => $content
            ];
            \Wechat::sendServiceMessage($post);
            unset($post);
            if (!empty($user)) {
                $post['touser'] = $toUser;
                $post['msgtype'] = 'news';
                $post['news'] = ['articles' =>
                    [
                        [
                            'title' => '轻戳此处完成注册，恭喜你离梦想的生活又近了一步~',
                            'description' => '立即成为超级合伙人，动动手指来赚钱~',
                            'url' => $href,
                            'picurl' => $icon
                        ]
                    ]
                ];
                \Wechat::sendServiceMessage($post);
                unset($post);
                $post['touser'] = $toUser;
                $post['msgtype'] = 'image';
                if (defined(SANDBOX) && SANDBOX) {
                    $post['image'] = ['media_id' => 'QeBsEsr5AC7pT5ToAon8qq0If1XHy2vCtw8cX6VwVmw'];
                } else {
                    $post['image'] = ['media_id' => '2gJdhIeEnykgePF9qRC2psKl9GphmHQ2shTv_Qp7nHI'];
                }
                \Wechat::sendServiceMessage($post);
            }
        }
    }
    /**
     * 发送选择问题菜单消息
     */
    private function sendChooseMenu($postArr){
        if(strtolower($postArr['Event']) == 'click' && $postArr['EventKey'] == 'customer'){//在线客服点击事件 发送菜单消息（选择问题类型）
            $toUser = $postArr['FromUserName'];
            $msgType = 'msgmenu';
            $content=[];
            $content['head_content']='请选择问题或输入问题编号';
            $group=\Wechat::$customer_group;
            foreach ($group as $key => $value) {
                unset($group[$key]['str']);
            }
            $content['list']=$group;
            $content['tail_content']='';
            \Wechat::sendCustomerMsg($toUser,$msgType,$content);
        }
    }
    /**
     * 发送常见问题
     */
    private function sendFaq($postArr,$group=''){
        $where='';
        if(!empty($group)) $where=" FIND_IN_SET('".$group."',`group`)";
        $kf_faq=KfFaq::where('cpm',$postArr['cpm'])->field('id,question')->where($where)->where('status',1)->where('is_delete',0)->order('sort asc')->select();
        $list=[];
        if(!$kf_faq->isEmpty()){
            $kf_faq_arr=$kf_faq->toArray();
            foreach ($kf_faq_arr as $key=>$value){
                $list[$key]['id']=$value['id'];
                $list[$key]['content']=$value['question'];
            }
        }
        if(empty($list)){
            return false;
        }
        $toUser = $postArr['FromUserName'];
        $kf_account = $postArr['KfAccount'];
        $msgType = 'msgmenu';
        $content=[];
        $content['head_content']='猜您想问的问题：';
        $content['list']=$list;
        $content['tail_content']='都不是? 请一句话描述您的问题，我们来帮您解决并转到合适的人工服务。';
        \Wechat::sendCustomerMsg($toUser,$msgType,$content,$kf_account);
    }
    /**
     * 发送评价菜单消息
     */
    private function sendCommentMenu($postArr){
        $toUser = $postArr['FromUserName'];
        $kf_account = $postArr['KfAccount'];
        $msgType = 'msgmenu';
        $content=[];
        $content['head_content']='您对本次服务是否满意呢？';
        $content['list']=[
                            ['id'=>'90090','content'=>'1、满意'],
                            ['id'=>'90091','content'=>'2、不满意']
                        ];
        $content['tail_content']='欢迎再次光临';
        \Wechat::sendCustomerMsg($toUser,$msgType,$content,$kf_account);
    }
    /**
     * 菜单点击之后 1、选择问题分配客服 2、会话结束评价
     */
    private function clickMenuResponse($postArr){
        //分组的前缀字符串
        $group=\Wechat::$customer_group;
        $group=array_combine(array_column($group,'id'),$group);
        $toUser = $postArr['FromUserName'];
        $fromUser = $postArr['ToUserName'];
        if(in_array($postArr['bizmsgmenuid'],['90090','90091'])){//会话结束评价
            \Wechat::sendCustomerMsg($toUser,'text','感谢您的评价');
        }elseif(array_key_exists($postArr['bizmsgmenuid'], $group)){//选择问题类型
            
            //菜单中定义的id
            $bizmsgmenuid=$postArr['bizmsgmenuid'];
            $group_str=empty($group[$bizmsgmenuid])? '':$group[$bizmsgmenuid]['str'];

            $onlincustomerlist=\Wechat::getCustomerOnlineList();
            $group_customer=[];
            if(empty($group_str)|| empty($onlincustomerlist)){//没有客服在线  返回固定客服消息
                \Wechat::sendCustomerMsg($toUser,'text','暂时没有客服人员接入，请稍后联系');
            }else{
                $getSession=\Wechat::getSession($toUser);
                if(!empty($getSession)&&!empty($getSession['kf_account'])){//已分配客服
                    echo '';
                }else{
                    //在线客服列表中 检出这个分组前缀的
                    foreach ($onlincustomerlist as $key => $value) {
                        if(strpos($value['kf_account'],$group_str.'@') !==false){//前缀中包含 分组字符串
                            $group_customer[]=$value;
                        }
                    }
                    if(empty($group_customer)){//当前分组客服不在线 分配给其他类型客服
                        $group_customer=$onlincustomerlist;
                    }
                    //随机一个客服 接入
                    $kf_account_array=$group_customer[mt_rand(0,count($group_customer)-1)];
                    //给客服和用户创建会话
                    \Wechat::createSession(['kf_account'=>$kf_account_array['kf_account'],'openid'=>$toUser]);
                    //取出所有客服 得到客服昵称
                    $customerList=\Wechat::getCustomerList();
                    $customerList=array_combine(array_column($customerList,'kf_account'),$customerList);
                    \Wechat::sendCustomerMsg($toUser,'text','很高兴为您服务,我是客服'.$customerList[$kf_account_array['kf_account']]['kf_nick'],$kf_account_array['kf_account']);
                    $time = time();
                    $msgType = 'transfer_customer_service';
                    $template = "<xml>
                                  <ToUserName><![CDATA[%s]]></ToUserName>
                                  <FromUserName><![CDATA[%s]]></FromUserName>
                                  <CreateTime>%s</CreateTime>
                                  <MsgType><![CDATA[%s]]></MsgType>
                                  <TransInfo>
                                    <KfAccount><![CDATA[%s]]></KfAccount>
                                  </TransInfo>
                                </xml>";

                    $info = sprintf($template,$toUser,$fromUser,$time,$msgType,$kf_account_array['kf_account']);
                    // echo $info;
                    echo '';
                }
            }
        }
    }
    /**
     *改版发送内容 本地（选择客服创建会话 并保存内容） 
     */
    public function newCreateSession($postArr)
    {
        if(!in_array($postArr['cpm'],[7,8])){
            return true;
        }
        $toUser = $postArr['FromUserName'];
        $cache_key='group_'.$toUser.'_'.$postArr['cpm'];
        $where='';
        $group_str=cache($cache_key);
        if(!empty($group_str) && $group_str['group']){
            $where=" FIND_IN_SET('".$group_str['group']."',`group`)";
        }
        //选择问题类型 或者选择了具体问题
        if(array_key_exists('bizmsgmenuid',$postArr)){
            //问题类型
            //分组的前缀字符串
            $group=\Wechat::$customer_group;
            $group=array_combine(array_column($group,'id'),$group);
            if(array_key_exists($postArr['bizmsgmenuid'], $group)){
                if(!empty($group[$postArr['bizmsgmenuid']])) {
                    cache($cache_key, ['group' => $group[$postArr['bizmsgmenuid']]['str']], 600);
                    //发送具体问题列表
                    $this->sendFaq($postArr, $group[$postArr['bizmsgmenuid']]['str']);
                    return true;
                }
            }else{
                //具体问题 直接发送答案
                $kf_faq=KfFaq::where('id',$postArr['bizmsgmenuid'])->field('id,answer')-where('status',1)->where('is_delete',0)->find();
                if(!empty($kf_faq) && !empty($kf_faq['answer'])){
                    $this->setCpmConfig($postArr['cpm']);
                    \Wechat::sendCustomerMsg($toUser,'text',$kf_faq['answer']);
                    return true;
                }
            }
        }
        switch (strtolower($postArr['MsgType'])) {
            case 'image':
                if($url=\Wechat::get('image',$postArr['MediaId'])){
                    $postArr['image_url']=$url;
                }
                break;
            case 'voice':
                if($url=\Wechat::get('voice',$postArr['MediaId'])){
                    $postArr['voice_url']=$url;
                }
                break;
            case 'shortvideo':
            case 'video':
                if($url=\Wechat::get('video',$postArr['MediaId'])){
                    $postArr['video_url']=$url;
                }
                if($thumb_url=\Wechat::get('thumb',$postArr['ThumbMediaId'])){
                    $postArr['thumb_url']=$thumb_url;
                }
                break;
        }
        //于客服建立的未过期会话
        $kf_session=KfSession::where('user_openid',$toUser)->where("kf_openid <> ''")->where('cpm',$postArr['cpm'])->where('is_delete',0)->where('expire_time > '.time())->find();
        if(!empty($kf_session)){
            //记录客服消息
            KfSessionMessage::create(['cpm'=>$postArr['cpm'],'session_id'=>$kf_session['id'],'from'=>$kf_session['user_openid'],'to'=>$kf_session['kf_openid'],'msg_type'=>$postArr['MsgType'],'content'=>json_encode($postArr),'time'=>time()]);
            //更新会话过期时间
            KfSession::where('id',$kf_session['id'])->update(['expire_time'=>time()+1800]);
        }else{
            //找一个客服
            $kf_array=[];
            //超过五分钟就认为客服不在线
            $kf=KfUser::where('expire_time > '.time())->where('cpm',$postArr['cpm'])->select();
            $group_kf=[];
            if(!empty($where)) $group_kf=KfUser::where('expire_time > '.time())->where('cpm',$postArr['cpm'])->where($where)->select();

            $kf_session_data=['cpm'=>$postArr['cpm'],'user_openid'=>$toUser,'expire_time'=>time()+1800,'time'=>time()];
            $kf_session_message_data=['cpm'=>$postArr['cpm'],'from'=>$toUser,'msg_type'=>$postArr['MsgType'],'content'=>json_encode($postArr),'time'=>time()];
            //临时会话
            $kf_session_short=KfSession::where('user_openid',$toUser)->where('kf_openid','')->where('cpm',$postArr['cpm'])->find();
            if($kf->isEmpty()){//创建  留言
                //查看留言条数 超过十条不记录 防刷
                if(KfSessionMessage::where('session_id',0)->where('to','')->where('from',$toUser)->count()>=10){
                    return true;
                }
                //创建临时会话
                if(!empty($kf_session_short)){
                    $kf_session_id=$kf_session_short['id'];
                }else{
                    $kf_session_id=KfSession::insertGetId($kf_session_data);
                }
                $kf_session_message_data['session_id']=$kf_session_id;
                $this->setCpmConfig($postArr['cpm']);
                \Wechat::sendCustomerMsg($toUser,'text','暂时没有客服人员接入，已经帮你留言给客服');
                //写入会话内容
                KfSessionMessage::create($kf_session_message_data);
                controller('\app\api\controller\Kf')->newMessageNotice();
            }else{
                if(empty($group_kf) || $group_kf->isEmpty()){
                    $group_kf=$kf;
                }
                $group_kf=$group_kf->toArray();
                //随机一个客服 接入
                $kf_array=$group_kf[mt_rand(0,count($group_kf)-1)];
                if(!empty($kf_array)){
                    $kf_session_message_data['to']=$kf_array['openid'];
                    //查询有没有历史会话
                    $history_session=KfSession::where('user_openid',$toUser)->where('kf_openid',$kf_array['openid'])->where('cpm',$postArr['cpm'])->find();
                    if(!empty($history_session)){//存在 更新过期时间
                        KfSession::where('id',$history_session['id'])->update(['is_delete'=>0,'expire_time'=>time()+1800]);
                        $kf_session_id=$history_session['id'];
                    }else{//没有历史会话 创建
                        $kf_session_data['kf_openid']=$kf_array['openid'];
                        $kf_session_id=KfSession::insertGetId($kf_session_data);
                    }
                    $kf_session_message_data['session_id']=$kf_session_id;
                    //写入会话内容
                    KfSessionMessage::create($kf_session_message_data);
                    $name=empty($kf_array['uname'])? '测试客服':$kf_array['uname'];
                    \Wechat::sendCustomerMsg($toUser,'text','会话创建成功，客服：'.$name.'为您服务！');
                    \Wechat::sendCustomerMsg($toUser,'text','您好');
                }else{//没找到客服  创建临时会话
                    //创建临时会话
                    if(!empty($kf_session_short)){
                        $kf_session_id=$kf_session_short['id'];
                    }else{
                        $kf_session_id=KfSession::insertGetId($kf_session_data);
                    }
                    $kf_session_message_data['session_id']=$kf_session_id;
                    //写入会话内容
                    KfSessionMessage::create($kf_session_message_data);
                    controller('\app\api\controller\Kf')->newMessageNotice();
                }
            }

        }
    }
    /**
     * 获取客服列表
     */
    public function getService(){
        $cpm = $this->get['cpm'];
        $this->setCpmConfig($cpm);
        $res = \Wechat::getService();
        echo $res;
    }

    /**
     * 获取图片素材列表
     */
    public function imageMaterial(){
        $cpm = $this->get['cpm'];
        $page = isset($this->get['p']) ? $this->get['p'] : 1;
        $this->setCpmConfig($cpm);
        $res = \Wechat::imageMaterial($page);
        echo $res;
    }

    public function getMenu(){
        $cpm = $this->get['cpm'];
        $this->setCpmConfig($cpm);
        $res = \Wechat::getMenu();
        echo $res;
    }


    private function setCpmConfig($cpm)
    {
        $company = Company::where('id', $cpm)->find();
        $token_arr = ['1' => 'ozvGRrYJ7555LJczRdckc7k75lZ57k2r', '2' => 'oO6bEV2oE40Z967226oeZ6EV065045iY', '3' => '', '4' => 'u9slLAJzoS00SJZjJP6SXS8LsjlxghsS', '5' => '', '6' => 'gterac3uzbb3u5fni30jc1owyg55euuj', '7' => 'xdnice2003abc', '8'=>'xdnice2019abc'];
        $appid = $company['wx_appid'];
        $appsecret = $company['wx_secret'];
        $token = $token_arr[$cpm];
        \Wechat::setConfig($appid, $appsecret, $token, $cpm);
        return true;
    }








}
